Ext.define('CA.dictionary.MetaTable',{
    extend: 'Ext.grid.Panel',
    xtype: 'CA.dictionary.MetaTable',

    uses: [
        'CA.base.LocaleCombo'
    ],

    cls: 'c-no-dirty',

    initComponent: function(){
        this.editing = Ext.create('Ext.grid.plugin.CellEditing');

        Ext.apply(this, {
            tbar: [
                {
                    text: 'Добавить',
                    scope: this,
                    handler: this.createField
                }
            ],
            columns: this.buildColumns(),
            plugins: [this.editing]
        });

        this.callParent();
    },

    buildColumns: function(){
        return [
            {
                text: 'Код поля',
                dataIndex: 'code',
                editor: 'textfield',
                flex: 1
            },
            {
                text: 'Тип поля',
                dataIndex: 'type',
                editor: {
                    xtype: 'CA.base.LocaleCombo',
                    locale: CA.locale.valueTypes
                },
                renderer: CA.localeRenderer(CA.locale.valueTypes),
                flex: 1
            },
            {
                text: 'Длина',
                dataIndex: 'length',
                editor: 'numberfield',
                width: 70
            },
            {
                text: 'По умолчанию',
                dataIndex: 'def',
                editor: 'textfield',
                width: 100
            },
            {
                xtype:'actioncolumn',
                width: 24,
                sortable: false,
                resizable: false,
                items: [{
                    icon: CA.content('app/icons/16/cancel.png'),
                    tooltip: 'Удалить',
                    scope: this,
                    handler: function(grid, rowIndex, colIndex) {
                        grid.store.removeAt(rowIndex);
                    }
                }]
            }
        ];
    },

    isValid: function(){
        var recs = this.store.data.items,
            data = Ext.pluck(recs, 'data'),
            valid = true,
            contains = Ext.Array.contains,
            codes = [];

        Ext.each(data, function(item){
            var code = item.code.toLocaleLowerCase();

            if(contains(codes, code)){
                valid = false;
                CA.error('Поле с кодом "'+item.code+'" дублируется.');
                return false;
            }

            codes.push(code);
        });

        return valid;
    },

    getMeta: function(){
        return Ext.pluck(this.store.data.items, 'data');
    },

    createField: function(){
        this.store.add({
            code: 'code',
            type: 'varchar',
            length: 64
        });
    }
});